package cart
{
    import mx.collections.ArrayCollection;
    import mx.collections.IViewCursor;
    import mx.collections.Sort;
    import mx.messaging.channels.StreamingAMFChannel;
    
    import spark.collections.SortField;

    public class ShoppingCart
    {
        [Bindable]
        public var items            :ArrayCollection  = new ArrayCollection();
        public var total            :Number = 0;
        public function ShoppingCart()
        {
            var prodSort:Sort = new Sort();
            var sortField:SortField = new SortField("product");
            prodSort.fields = [sortField];
            items.sort = prodSort;
            items.refresh();
        }
        public function addItem(item:ShoppingCartItem):void
        {
            if(isItemInCart(item))
            {
                updateItem(item);       
            }else{
                items.addItem(item);
            }
            calculateTotal();
            trace(item);
        }
        public function removeItem(item:ShoppingCartItem):void
        {
            var cursor:IViewCursor = items.createCursor();
            if(cursor.findFirst(item))
            {
                cursor.remove();
            }
        }
        public function toString():String
        {
            return "[ShoppingCart $"+ total +"]" + items;
        }
        public function getItemInCart(item:ShoppingCartItem):ShoppingCartItem
        {
            var existingItem:ShoppingCartItem;
/*            for(var i:int=0;i<items.length;i++)
            {
                existingItem = items[i] as ShoppingCartItem;
                if(existingItem.product == item.product)
                {
                    return existingItem;
                }
            }*/
            var cursor:IViewCursor = items.createCursor();
            if(cursor.findFirst(item))
            {
                existingItem = cursor.current as ShoppingCartItem;
            }
            return existingItem;
        }
        public function isItemInCart(item:ShoppingCartItem):Boolean
        {
            var sci:ShoppingCartItem = getItemInCart(item);
            return sci!=null;
        }
        public function updateItem(item:ShoppingCartItem):void
        {
            var existingItem:ShoppingCartItem = getItemInCart(item);
            existingItem.quantity+=item.quantity;
//            existingItem.calculateSubTotal();
        }
        public function calculateTotal():void
        {
            var newTotal:Number = 0;
            var existingItem:ShoppingCartItem;
            for(var i:int=0;i<items.length;i++)
            {
                existingItem = items[i] as ShoppingCartItem;
                newTotal+=existingItem.subTotal;
            }
            this.total = newTotal;
        }
            
    }
}